package com.sofar.jwt.Interceptor;

import com.sofar.jwt.entity.TblUser;
import com.sofar.jwt.utils.JWTUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shiguorang
 * @version 1.0.0
 * @ClassName UserLoginInterceptor
 * @Description 拦截器
 * @createTime 2022年08月12日 15:52:00
 */
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //http的header中获得token
        String token = request.getHeader(JWTUtil.TOKEN);
        if (token == null || token == ""){
            throw new RuntimeException("请先登录");
        }
        //验证token
        TblUser sub = JWTUtil.validateToken(token);
        if (sub == null){
            throw new RuntimeException("token验证失败");
        }
        if (JWTUtil.isNeedUpdate(token)){
            String newToken  = JWTUtil.createToken(sub);
            response.setHeader(JWTUtil.TOKEN,newToken);
        }
        return true;
    }
}
